package com.ld.curator.tools;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @author:ld
 * @create:2020-04-30 15:31
 * @description: 分布式锁
 */
public class CuratorLock {

    private static String lock_path = "/curator_lock_path";

    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString("127.0.0.1:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000,3))
            .build();

    public static void main(String[] args) {
        //开启客户端连接
        client.start();

        //创建分布式锁对象
        InterProcessMutex lock = new InterProcessMutex(client, lock_path);

        //创建计数器，用于阻塞线程，等待所有线程都创建完成，在同时执行业务
        CountDownLatch countDownLatch = new CountDownLatch(1);

        //循环创建30个线程
        for(int i = 0;i < 3; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //阻塞
                        countDownLatch.await();
                        //获取锁对象
                        lock.acquire();
                        Thread.sleep(3000);
                        //执行业务逻辑
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss|SSS");
                        String orderNo = simpleDateFormat.format(new Date());
                        System.out.println("生成的订单号：" + orderNo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            //释放锁
                            lock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
        //计数器减1
        countDownLatch.countDown();
    }
}
